/**
 * ValidCheck Object
 * Author: Fgang
 * Date: 2013 5
 * Des: 数值型参数校验模块。
 */
var ValidCheck = (function () {
    var PatternPos = 0, haveLeftBraceCount = 0, Pattern = "", CheckValue = "", //
        LeftBracePattern = /^\s*\(\s*/, //
        RightBracePattern = /^\s*\)\s*/, //
        LeftDataValidPattern = /^\s*(>|<|>=|<=|==|!=)\s*(-?\d*\.?\d+|-?0[xX][a-fA-F0-9]+)/, //
        RightDataValidPattern = /^\s*(-?\d*\.?\d+|-?0[xX][a-fA-F0-9]+)\s*(>|<|>=|<=|==|!=)/, //
        RangPatternStep = /^\s*([\[\{])\s*(-?\d*\.?\d+|-?0[xX][a-fA-F0-9]+)\s*,\s*(-?\d*\.?\d+|-?0[xX][a-fA-F0-9]+)\s*((:)\s*(-?\d*\.?\d+|-?0[xX][a-fA-F0-9]+)\s*)?([\]\}])\s*/, //
        NumberPattern = /^\s*(-?\d*\.?\d+|-?0[xX][a-fA-F0-9]+)\s*$/;

    //去除十进制数的前置0，以免后续校验将其当作8进制处理
    function dealWithOctal(value) {
        var sixteenRegex = /-?0[xX][a-fA-F0-9]+/, //
            tenRegex = /(-?)0*(\d*\.?\d+)/, matches = [];
        if (!sixteenRegex.test(value)) {
            matches = tenRegex.exec(value);
            return matches[1] + (String(matches[2]).indexOf(".") === 0 ? "0" : "") + matches[2];
        } else {
            return value;
        }
    }

    function IsValid(pattern, checkValue) {
        PatternPos = 0;
        haveLeftBraceCount = 0;
        Pattern = pattern;
        CheckValue = checkValue;
        try {
            if (!NumberPattern.test(CheckValue.toString())) {
                // 参数值非数值
                return false;
            }
            //去除十进制数的前置0，以免后续校验将其当作8进制处理
            CheckValue = dealWithOctal(NumberPattern.exec(CheckValue)[1]);

            return Boolean(OrExprMatch());
        } catch (error) {
            throw new SyntaxError("Invalid Syntax");
        }
    }

    function OrExprMatch() {
        var exprResult = AndExprMatch(), OrOperatorPattern = /^\s*\|\|\s*/, SearchString = "", matches = false;

        while (PatternPos < Pattern.length) {
            SearchString = Pattern.substring(PatternPos);
            matches = OrOperatorPattern.exec(SearchString);
            if (matches) {
                PatternPos += matches[0].length;
                exprResult = exprResult || AndExprMatch();
            } else if (Pattern.charAt(PatternPos) === ' ' || Pattern.charAt(PatternPos) === '\t' || //
                Pattern.charAt(PatternPos) === '\r' || Pattern.charAt(PatternPos) === '\n') {
                /* 跳过空白字符  */
                PatternPos += 1;
            } else if (haveLeftBraceCount <= 0 && Pattern.charAt(PatternPos) === ')') {
                throw new SyntaxError(" ')' Mismatch '('");
            } else if (Pattern.charAt(PatternPos) === ',') {
                throw new SyntaxError("Invalid Syntax 1");
            } else {
                /* 非法语法  */
                return exprResult;
            }
        }
        return exprResult;
    }

    function AndExprMatch() {
        var exprResult = TermExprMatch(), AndOperatorPattern = /^\s*&&\s*/, SearchString = "", matches = false;

        while (PatternPos < Pattern.length) {
            SearchString = Pattern.substring(PatternPos);
            matches = AndOperatorPattern.exec(SearchString);
            if (matches) {
                PatternPos += matches[0].length;
                exprResult = exprResult && TermExprMatch();
            } else if (Pattern.charAt(PatternPos) === ' ' || Pattern.charAt(PatternPos) === '\t' || //
                Pattern.charAt(PatternPos) === '\r' || Pattern.charAt(PatternPos) === '\n') {
                /* 跳过空白字符  */
                PatternPos += 1;
            } else if (haveLeftBraceCount <= 0 && Pattern.charAt(PatternPos) === ')') {
                throw new SyntaxError(" ')' Mismatch '('");
            } else if (Pattern.charAt(PatternPos) === ',') {
                throw new SyntaxError("Invalid Syntax 2");
            } else {
                /* 非法语法  */
                return exprResult;
            }
        }
        return exprResult;
    }

    function TermExprMatch() {
        var exprResult, ret = false, curreentHaveLeftBrace = false, //
            SearchString = "", matches = false, //
            expr = "", leftOP = "", rightOP = "", step = "1";

        while (PatternPos < Pattern.length) {
            SearchString = Pattern.substring(PatternPos);
            matches = LeftBracePattern.exec(SearchString);
            if (matches) {
                /* 匹配左刮号 */
                PatternPos += matches[0].length;
                curreentHaveLeftBrace = true;
                haveLeftBraceCount += 1;
                ret = OrExprMatch();
            } else if (Pattern.charAt(PatternPos) === ' ' || Pattern.charAt(PatternPos) === '\t' || //
                Pattern.charAt(PatternPos) === '\r' || Pattern.charAt(PatternPos) === '\n') {
                /* 跳过空白字符  */
                PatternPos += 1;
            } else if (curreentHaveLeftBrace) {
                /* 匹配右刮号 */
                SearchString = Pattern.substring(PatternPos);
                matches = RightBracePattern.exec(SearchString);
                if (matches) {
                    PatternPos += matches[0].length;
                    haveLeftBraceCount -= 1;
                    curreentHaveLeftBrace = false;
                    return ret;
                } else {
                    /* 返回上层，继续处理 */
                    throw new SyntaxError("Invalid Syntax 3");
                }
            } else {
                SearchString = Pattern.substring(PatternPos);
                matches = LeftDataValidPattern.exec(SearchString);
                if (matches) {
                    PatternPos += matches[0].length;
                    expr = "";
                    expr = expr.concat(CheckValue.toString(), " ", matches[0]);
                    return eval(expr);
                }

                matches = RightDataValidPattern.exec(SearchString);
                if (matches) {
                    PatternPos += matches[0].length;
                    expr = "";
                    expr = expr.concat(matches[0], " ", CheckValue.toString());
                    return eval(expr);
                }

                matches = RangPatternStep.exec(SearchString);
                if (matches) {
                    PatternPos += matches[0].length;
                    expr = "";
                    leftOP = "";
                    rightOP = "";
                    step = "1";

                    if (matches[1] === '[') {
                        leftOP = " <= ";
                    } else if (matches[1] === '{') {
                        leftOP = " < ";
                    }

                    if (matches[5] === ':') {
                        step = matches[6];
                    }

                    if (matches[7] === ']') {
                        rightOP = " <= ";
                    } else if (matches[7] === '}') {
                        rightOP = " < ";
                    }

                    if (step.indexOf(".") == -1) {
                        expr = expr.concat(matches[2], leftOP, CheckValue.toString(), " && ", //
                            CheckValue.toString(), rightOP, matches[3], " && ", "Math.abs( ( (", //
                            CheckValue.toString(), " - ", matches[2], " ) * 1000000000 )", " % ", " ( ", //
                            step, " * 1000000000) ) < 1");
                        return eval(expr);

                    } else {
                        var val = CheckValue.toString().split(".")[1] || "";
                        if (val.length > step.split(".")[1].length) {
                            return false;
                        }

                        var multiValue = step.indexOf(".") > -1 ? Math.pow(10, step.split(".")[1].length) : 1, //
                            minusValue = step.indexOf(".") > -1 ? Math.round((CheckValue.toString() - matches[2]) * multiValue) : (CheckValue.toString() - matches[2]);
                        //
                        step = step * multiValue;

                        expr = expr.concat(matches[2], leftOP, CheckValue.toString(), " && ", //
                            CheckValue.toString(), rightOP, matches[3], " && ", "Math.abs( ( (", //
                            minusValue, " ) * 1000000000 )", " % ", " ( ", //
                            step, " * 1000000000) ) < 1");
                        return eval(expr);
                    }

                }

                matches = NumberPattern.exec(SearchString);
                if (matches) {
                    PatternPos += matches[0].length;
                    expr = "";
                    expr = expr.concat(CheckValue.toString(), "==", parseInt(matches[0], 10));
                    return eval(expr);
                }

                /* 非法语法  */
                throw new SyntaxError("Invalid Syntax");
            }
        }
        /* 非法语法  */
        if (haveLeftBraceCount > 0) {
            throw new SyntaxError(" '(' Mismatch ')'");
        } else {
            throw new SyntaxError("Invalid Syntax");
        }
    }

    return {
        IsValid: IsValid
    };
}());

/**
 * 操作黑白名单
 */
var RowEditor = (function () {
    var $$, historySelect = [], preSelect = -1, maxIndex = 100, check = "", //
        valueChange = "", initValues = [], node = "";

    /*  */
    function unSelect() {
        $$(".x-grid3-row").removeClass("x-grid3-row-selected");
        historySelect = [];
    }

    /* */
    function doCreateRow(index, val) {
        if ($$.trim(val) === "") {
            return "";
        }

        var i = 0, html = "<div class='x-grid3-row x-grid3-frist' onclick='top.RowEditor.selectRow(this)'>" + //
            "<table class='x-grid3-row-table' cellspacing='0' cellpadding='0' border='0'>" + //
            "<tr><td class='x-grid3-col x-grid3-cell x-grid3-td-number x-grid3-cell-first' tabindex='0'" + //
            "        style='width:40px;" + /* " background-image:url(./images/grid3-special-col-bg.gif);"*/" '>%s</td>" + //
            "<td class='x-grid3-cell-other'>%s</td></tr></table></div>", //
            rep = function () {
                var ret = "";

                if (i === 0) {
                    ret = index;
                } else {
                    ret = val;
                }
                i += 1;
                return ret;
            };

        return html.replace(/%s/g, rep);
    }

    /* */
    function getAllValues() {
        var vVal = [], set = $$(".x-grid3-row").find("td"), i = 0;

        for (i = 0; i < set.length; i += 1) {
            if ((i % 2) === 1) {
                vVal.push($$(set[i]).text());
            }
        }

        return vVal;
    }

    /* */
    function reSort() {
        var i = 0, index = 1, html = [], vVal = getAllValues();

        if (typeof valueChange === 'function') {
            valueChange(vVal, node);
        }

        for (i = 0; i < vVal.length; i += 1) {
            html.push(doCreateRow(index, vVal[i]));
            index += 1;
        }

        $$(".x-grid3-row").remove();
        $$($$(".x-grid3-body")[0]).append(html.join(''));
        maxIndex = index;
    }

    /**
     公有
     */

    /* */
    function ItemSelect(nd) {
        var CtrlBtn = top.globalCtrlBtn, ShiftBtn = top.globalShiftBtn, begin = -1, end = -1, set = [], i = 0;

        if (CtrlBtn === true && ShiftBtn === true) {
            CtrlBtn = false;
            ShiftBtn = false;
        }

        if (CtrlBtn === false && ShiftBtn === false) {
            if (!$$(nd).hasClass("x-grid3-row-selected")) {
                $$(nd).addClass("x-grid3-row-selected");
                historySelect.push($$(nd).index());
                preSelect = $$(nd).index();
            } else {
                preSelect = $$(nd).index();
                $$(nd).removeClass("x-grid3-row-selected");
                historySelect.splice($.inArray(preSelect, historySelect), 1);
            }
        }

        if (CtrlBtn === true && ShiftBtn === false) {
            $$(nd).addClass("x-grid3-row-selected");
            historySelect.push($$(nd).index());
            preSelect = $$(nd).index();
        }

        if (CtrlBtn === false && ShiftBtn === true) {
            if (preSelect !== -1) {
                begin = preSelect < $$(nd).index() ? preSelect : $$(nd).index();
                begin = begin - 1;
                end = preSelect + $$(nd).index() - begin;
                end = end - 1;

                set = $$(".x-grid3-row");

                for (i = begin; i < end; i += 1) {
                    $$(set[i]).addClass("x-grid3-row-selected");
                    historySelect.push($$(set[i]).index());
                }
            }
        }
    }

    /* */
    function doRemoveList() {
        var set = $$(".x-grid3-row-selected").remove();
        reSort();
    }

    /* */
    function editorConfirm() {
        var editor = $$("#add-del-list-updata-editor-input"), val = $$(editor).val(), html = "";

        html = doCreateRow(maxIndex, val);

        if (typeof check === 'function') {
            if (check(val, node) === false) {
                return;
            }
        }

        $$($$(".x-grid3-body")[0]).prepend(html);
        reSort();
    }

    /* */
    function selectAll() {
        $$("#x-grid3-scroller").fadeOut(200);

        if ($$(".x-grid3-row").hasClass("x-grid3-row-selected")) {
            $$(".x-grid3-row").removeClass("x-grid3-row-selected");
            historySelect = [];
        } else {
            $$(".x-grid3-row").addClass("x-grid3-row-selected");
        }

        $$("#x-grid3-scroller").fadeToggle(200);
    }

    /* */
    function openList(paramObj) {
        if (typeof paramObj === 'object') {
            check = paramObj.check;
            valueChange = paramObj.valueChange;
            initValues = paramObj.values;
            node = paramObj.node;
        }

        $$(".x-grid3-row").remove();

        if (paramObj.title.length > 0) {
            $$("#list-table-title").text(paramObj.title);
        }

        var items = [], i = 0;
        for (i = 0; i < initValues.length; i += 1) {
            items.push(doCreateRow(i + 1, initValues[i]));
        }
        $$($$(".x-grid3-body")[0]).append(items.join(''));

        $$("#add-del-list").show(100);
    }

    function doClose() {
        $$("#add-del-list").hide(100);
    }

    /* */
    function init($, DivContainerID) {
        $$ = $;
        historySelect = [];
        var html = "<br/><br/>" + //
            "<div id='add-del-list' class='x-panel' style='display:none;'>" + //
            "  <div id='add-del-list-main' class='x-panel-bwrap'>" + //
            "    <div id='add-del-list-body' class='x-panel-body x-border-layout-ct' style='height: 363px;'>" + //
            "      <div id='add-del-list-grid-action' class='x-toolbar x-small-editor x-toolbar-layout-ct'>" + //
            "        <table class='x-toolbar-ct' cellspacing='0'>" + //
            "          <tr>" + //
            "            <td style='width:60px;'><a class='btn1' id='rowEditorSelectAllBtn'> <span  style='border: 0px none;'>" + top.T.BTN.SelectAll + "</span></a></td>" + //
            "            <td style='width:60px;'><a class='btn1' id='rowEditorRemoveBtn'> <span style='border: 0px none;'>" + top.T.BTN.Delete + "</span> </a></td>" + //
            "            <td style='padding-left:40px; width:100px;'><input id='add-del-list-updata-editor-input' type='text' height='18'></td>" + //
            "            <td><a id='add-del-list-updata-editor-confirm' class='btn1'><span style='border: 0px none;'>" + top.T.BTN.Add + "</span></a></td>" + //
            "          </tr>" + //
            "        </table>" + //
            "      </div>" + //
            "      <div class='x-panel-body x-panel-body-noheader' style='height: 330px; margin: auto;'>" + //
            "        <div class='x-grid3-title'><table><tbody><tr><td class='tdIndex'>" + top.T.ParamView.Index + "</td><td id='list-table-title'></td></tr></tbody></table></div>" + //
            "        <div id='x-grid3-scroller' class='x-grid3-scroller' style='height: 310px;'>" + //
            "          <div class='x-grid3-body'></div>" + //
            "        </div>" + //
            "      </div>" + //
            "    </div>" + //
            "  </div>" + //
            "</div>";
        $$("#" + DivContainerID).empty().append(html);
        $$("#rowEditorRemoveBtn").bind("click", top.RowEditor.remove);
        $$("#rowEditorSelectAllBtn").bind("click", top.RowEditor.selectAll);
        $$("#add-del-list-updata-editor-confirm").bind("click", top.RowEditor.addAction);
    }

    return {
        init: init,
        selectAll: selectAll,
        selectRow: ItemSelect,
        remove: doRemoveList,
        addAction: editorConfirm,
        openList: openList,
        allValues: getAllValues,
        doClose: doClose
    };

}());

/**
 * 数组列表显示、输入、保存
 */
var ArrayView = (function () {
    var arrayViewNODE = '';

    /**
     * 显示数组列表输入框
     * @param {Object} node, DOM Object that was clicked.
     */
    function show(node) {
        arrayViewNODE = node;

        $("#configTable").empty();
        $("#warning_tit").text('');
        $("#array_table_submit").unbind().bind('click', (ArrayView.submit));

        var structName = $(node).attr("structname"), //
            memberName = $(node).attr("name"), //
            memberID = $(node).attr("memberid"), //
            structDesc = localDB.T_search("c_param", "StructName", structName), //
            MemberNameIndex = top.c_paramRowIndex.MemberName, //
            MemberIDIndex = top.c_paramRowIndex.MemberID, //
            TypeDescIndex = top.c_paramRowIndex.TypeDesc, //
            WebTypeIndex = top.c_paramRowIndex.WebType, //
            LevelIndex = top.c_paramRowIndex.Level, //
            memberDesc = null, i = 0, len = 0;

        for (i = 0, len = structDesc.length; i < len; i += 1) {
            if (structDesc[i][MemberIDIndex] === memberID) {
                memberDesc = structDesc[i];
                break;
            }
        }

        var xx = 0, tips = '', changeable = 1, changeableCss = "", //
            notChangeablecss = "", role = GetCookie('role'), //
            webType = parseInt(memberDesc[WebTypeIndex], 10), rowCnt = 0, //
            danwei = "", fanwei = "", spdanwei = [];

        if (role !== top.Roles.Root) {
            if ((webType >= 10 && webType <= 19) || (webType >= 100 && webType <= 119)) {
                if ((!node.forceChangable)) {
                    changeableCss = 'readonly="readonly"';
                    notChangeablecss = ";background:#ffffff;opacity:0.4;filter:alpha(opacity=50);";
                }
            }
        }
        rowCnt = window.parseInt(Transfer.parseDbColumn(memberDesc[TypeDescIndex]), 10);

        spdanwei = Transfer.parseDbColumn(memberDesc[LevelIndex]).split('|');
        if (spdanwei.length > 0) {
            danwei = spdanwei[0];
        }

        if (spdanwei.length >= 2) {
            if (top.Language === "EN") {
                fanwei = "(" + spdanwei[6] + ")";
            } else {
                fanwei = "(" + spdanwei[1] + ")";
            }
        }
        $("#dialog_tit").text(top.T.Main.ArrayConfig + "(" + top.T.Main.Unit + ":" + danwei + ")" + fanwei);

        var i = 1, tabTom = "<tr>", tabFlag = "<tr>", id = "", view = "", j = 0, colsCnt = 11, rowLen = 0;
        if ((rowCnt % colsCnt) !== 0) {
            rowLen = window.parseInt(rowCnt / colsCnt) + 1;
        } else {
            rowLen = window.parseInt(rowCnt / colsCnt);
        }

        var table_height = 0;
        if (rowLen <= 8) {
            table_height = 46 * rowLen + 4;
        } else {
            table_height = 46 * 8;
        }
        table_height = table_height + 10;

        if (rowCnt < 128) {
            $("#array_table").css("left", "25%");
            $("#array_table").css("top", "10%");
        }
        $("#configTable_div").width(660);
        $("#configTable_div").height(table_height);

        for (i = 1; i <= rowCnt; i += 1) {
            j += 1;
            tabFlag = tabFlag + "<td>" + (i - 1) + "</td>";
            tabTom = tabTom + "<td>" + "<input structname='" + structName + "' memberName='" + memberName + //
                "' memberid='" + memberID + "' class='textInput' " + changeableCss + " style='" + notChangeablecss + //
                "' onFocus='input_focus(this)' onBlur='input_blur(this)' onchange='input_changed(this)' id='int" + //
                (i - 1) + "' value='' type='text'  " + tips + " />" + "</td>";

            if (i === rowCnt) {
                tabTom = tabTom + "</tr>";
                tabFlag = tabFlag + "</tr>";
                view = view + tabFlag + tabTom;
                break;
            }

            if (j === colsCnt) {
                tabTom = tabTom + "</tr>";
                tabFlag = tabFlag + "</tr>";
                view = view + tabFlag + tabTom;
                tabTom = "<tr>";
                tabFlag = "<tr>";
                j = 0;
            }
        }
        $("#configTable").append(view);

        //获取数组成员号与成员值，保存在arr数组中，单数为成员号，双数为成员值
        var str = $(node).val(), arr = [], pat = /\d*/g;
        xx = str.match(pat);
        i = 0;

        for (i = 0; i < xx.length; i += 1) {
            if (xx[i] !== "") {
                arr.push(xx[i]);
            }
        }

        //向input框输入相应的值
        var num = 0, tmp;
        for (i = 0; i < arr.length; i += 2) {
            num = window.parseInt(arr[i], 10);
            temp = "#int" + num;
            $(temp).val(arr[i + 1]);
        }

        $("#array_table").focus();
        $("#coverPage").show();
        $("#array_table").show();
    }

    /**
     * 关闭数组列表输入框
     */
    function close() {
        $("#array_table").hide();
        $("#coverPage").hide();
    }

    /**
     * 数组表保存
     */
    function submit() {
        //生成数组显示方式,作为返回服务器的字符串
        var name_Base = "a", //存放数组名
            name = name_Base + "[id]", re_Str = "", //存放返回值
            length = $("#array_table input[type='text']").length, /* input框的个数，也就是参数的最大个数 */
            id = "", arr_i = [], value = "", re_str_b = "", //
            structName = $("#int0").attr("structname"), //
            memberName = $("#int0").attr("membername"), //
            memberID = $("#int0").attr("memberid"), //
            structDesc = localDB.T_search("c_param", "StructName", structName), //
            MemberNameIndex = top.c_paramRowIndex.MemberName, //
            MemberIDIndex = top.c_paramRowIndex.MemberID, //
            RegexIndex = top.c_paramRowIndex.Regex, //
            memberDesc = null, i = 0, len = 0, //
            RegexStr = "", Regex, fTest = false;

        for (i = 0, len = structDesc.length; i < len; i += 1) {
            if (structDesc[i][MemberIDIndex] === memberID) {
                memberDesc = structDesc[i];
                break;
            }
        }
        RegexStr = Transfer.parseDbColumn(memberDesc[RegexIndex]).replace(/\\\\/g, "\\");

        for (i = 0; i < length; i += 1) {
            id = "#int" + (i);
            //这是input元素的name命名格式，具体命名生成过程在显示生成函数中
            value = $(id).val();
            if (typeof (RegexStr) !== "undefined" && RegexStr !== "") {
                Regex = new RegExp(RegexStr, "g");
                fTest = Regex.test(value);

                if (!fTest) {
                    $("#warning_tit").text(top.T.AlertInfo.FocusValueOutRange);
                    $(id).focus();
                    return;
                }
            }

            arr_i.push(i, value);
            re_str_b = re_str_b + value + ",";
        }
        re_str_b = re_str_b.replace(/,*$/, '');

        var temp = "";
        for (i = 0; i < arr_i.length; i += 2) {
            // Bug 解决 : 修复数组允许为空时，解释错误的问题
            if (arr_i[i + 1] != "") {
                temp = name;
                temp = temp.replace("id", arr_i[i]) + "=" + arr_i[i + 1] + ",";
                re_Str = re_Str + temp;
            }
        }
        var tips = re_Str + "*" + re_str_b, tips_arr = [];
        if (tips != null) {
            tips_arr = tips.split("*");
            if (arrayViewNODE.value != tips_arr[0]) {
                arrayViewNODE.value = tips_arr[0];
                $(arrayViewNODE).attr("proto", tips_arr[1]);
                $(arrayViewNODE).keyup();

                try {
                    var c$ = document.getElementById("contentMainFrame").contentWindow.$;
                    c$(arrayViewNODE).keyup();
                } catch (e) {
                }
            }
        }

        $("#array_table").hide();
        $("#coverPage").hide();
    }

    return {
        show: show,
        close: close,
        submit: submit
    };

}());

/**
 * 数组列表显示、输入、保存
 */
var BitMapView = (function () {
    var arrayViewNODE = '';

    /**
     * 显示数组列表输入框
     * @param {Object} node, DOM Object that was clicked.
     */
    function show(node) {
        arrayViewNODE = node;

        $("#configTable").empty();
        $("#warning_tit").text('');
        $("#array_table_submit").unbind().bind('click', (BitMapView.submit));

        var structName = $(node).attr("structname"), //
            memberName = $(node).attr("name"), //
            memberID = $(node).attr("memberid"), //
            structDesc = localDB.T_search("c_param", "StructName", structName), //
            MemberNameIndex = top.c_paramRowIndex.MemberName, //
            MemberIDIndex = top.c_paramRowIndex.MemberID, //
            TypeDescIndex = top.c_paramRowIndex.TypeDesc, //
            WebTypeIndex = top.c_paramRowIndex.WebType, //
            LevelIndex = top.c_paramRowIndex.Level, //
            memberDesc = null, i = 0, j = 0, len = 0, descObj = {}, colsCnt = 0, rowCnt = 0, totalCnt = 0,
            table_height = 0, webType = 0, changeable = 1, changeableCss = "", notChangeablecss = "", tips = "",
            role = GetCookie('role'), protoVal = 0;
        ;

        //获取参数描述
        for (i = 0, len = structDesc.length; i < len; i += 1) {
            if (structDesc[i][MemberIDIndex] === memberID) {
                memberDesc = structDesc[i];
                break;
            }
        }

        descObj = eval('(' + $.trim(memberDesc[TypeDescIndex]) + ')');
        totalCnt = descObj.total;
        colsCnt = descObj.cols;
        tips = descObj.tips;
        webType = parseInt(memberDesc[WebTypeIndex], 10);
        //

        //根据总数与列数，计算出行数（rowCnt）
        if ((totalCnt % colsCnt) !== 0) {
            rowCnt = window.parseInt(totalCnt / colsCnt) + 1;
        } else {
            rowCnt = window.parseInt(totalCnt / colsCnt);
        }

        //由行数算出表格的高度
        table_height = 0;
        if (rowCnt <= 8) {
            table_height = 46 * rowCnt + 4;
        } else {
            table_height = 46 * 8;
        }
        table_height = table_height + 10;

        //超级用户处理，强制可改
        if (role !== top.Roles.Root) {
            if ((webType >= 10 && webType <= 19) || (webType >= 100 && webType <= 119)) {
                if ((!node.forceChangable)) {
                    changeableCss = 'readonly="readonly"';
                    notChangeablecss = ";background:#ffffff;opacity:0.4;filter:alpha(opacity=50);";
                }
            }
        }

        //添加标题
        $("#dialog_tit").text(top.T.Main.ArrayConfig);

        //设置表格位置
        $("#array_table").css("left", "10px");
        $("#array_table").css("top", "10px");

        //设置表格高度和宽度
        $("#configTable_div").width(660);
        $("#configTable_div").height(table_height);

        //生成表格元素
        var ri = 0, cj = 0, topHtml, rowHtml = '', html = '';

        topHtml = "<tr><td></td>";
        for (cj = 0; cj < colsCnt; cj++) {
            topHtml = topHtml + "<td>" + (cj + 1) + "</td>";
        }
        topHtml = topHtml + "</tr>";
        html = html + topHtml;

        for (ri = 0; ri < rowCnt; ri++) {

            rowHtml = "<tr>" + "<td>" + tips + (ri + 1) + "</td>";
            for (cj = 0; cj < colsCnt; cj++) {
                rowHtml += "<td>";

                if ((ri * colsCnt) + (cj + 1) <= totalCnt) {//class='textInput'
                    rowHtml = rowHtml + "<input type='checkbox' structname='" + structName + "' memberName='" + memberName + "' memberid='" + memberID + "' id='bitCheckbox" + ((ri * colsCnt) + cj + 1) + "' />";
                }

                rowHtml += "</td>";
            }

            rowHtml = rowHtml + "</tr>";
            html += rowHtml;
        }

        $("#configTable").append(html);

        //赋值
        var bitOperator = 1, id = "";
        protoVal = $(node).attr("proto");

        try {
            for (cj = 0; cj < 31; cj++) {

                id = "#bitCheckbox" + (cj + 1).toString();
                if (bitOperator & parseInt(protoVal)) {
                    $(id).attr("checked", true);
                }
                bitOperator = (bitOperator << 1);
            }
        } catch (e) {
        }

        $("#array_table").focus();
        $("#coverPage").show();
        $("#array_table").show();
    }

    /**
     * 关闭数组列表输入框
     */
    function close() {
        $("#array_table").hide();
        $("#coverPage").hide();
    }

    /**
     * 数组表保存
     */
    function submit() {
        var value = 0, valueStack = "", i = 0, valueStr = "";

        var boxes = $('input[id^=bitCheckbox]');

        for (i = 0; i < boxes.length; i++) {
            if ($(boxes[i]).is(":checked")) {
                //valueStack.push(1);
                valueStack = "1" + valueStack;
            } else {
                //valueStack.push(0);
                valueStack = "0" + valueStack;
            }
        }

        value = parseInt(valueStack, 2);
        valueStr = "bitMap(" + value + ")";

        if (arrayViewNODE.value !== valueStr) {
            arrayViewNODE.value = valueStr;
            $(arrayViewNODE).attr("proto", value);
            $(arrayViewNODE).keyup();

            try {
                var c$ = document.getElementById("contentMainFrame").contentWindow.$;
                c$(arrayViewNODE).keyup();
            } catch (e) {
            }
        }

        $("#array_table").hide();
        $("#coverPage").hide();
    }

    return {
        show: show,
        close: close,
        submit: submit
    };

}());

/**
 * 帮助模块
 * @author fgang
 */
var Help = (function () {
    var xmldom = null, lan = "Chinese", showMemberNameIndex, memberNameIndex, //
        showStructNameIndex, structNameIndex;

    function init() {
        var root = null;

        $.ajax({
            type: "post",
            url: "/xml/help.xml",
            async: false,
            dataType: "xml",
            success: function (data, textStatues) {
                root = data;
            },
            error: function () {
                throw new Error("get xml error");
            }
        });
        return root;
    }

    function initVars() {
        showMemberNameIndex = top.c_paramRowIndex.MemberCnName;
        memberNameIndex = top.c_paramRowIndex.MemberName;

        showStructNameIndex = top.c_paramRowIndex.StructCnName;
        structNameIndex = top.c_paramRowIndex.StructName;

        if (top.Language === "EN") {
            showMemberNameIndex = memberNameIndex;
            showStructNameIndex = structNameIndex;
            lan = "English";
        }
    }

    /**
     * @param {Object} $elements, JQuery elements
     */
    function get($elements) {
        if (!xmldom) {
            xmldom = init();
            initVars();
        }
        var StructIDs = [], MemberNames = [], MemberIDs = [];

        $elements.each(function (index) {
            MemberNames.push($($(this).parent().parent().parent().children("td")[0]).text());
            StructIDs.push($(this).attr("structid"));
            MemberIDs.push($(this).attr("memberid"));
        });
        return filter(StructIDs, MemberNames, MemberIDs);
    }

    function filter(StructIDs, MemberNames, MemberIDs) {
        if (xmldom) {
            var i = 0, MemberID, MemberName, StructID, xpath, nodeTip = "", //
                tipValue = "", resultStr = "";

            for (i = 0; i < MemberIDs.length; i += 1) {
                MemberID = MemberIDs[i];
                MemberName = MemberNames[i];

                tipValue = getMemberValue(MemberID);

                if (tipValue !== "") {
                    resultStr += "<label id='Tips_" + MemberID + "'>";
                    resultStr += "<b>" + MemberName + "</b>" + tipValue + "</label>";
                }
            }
            return resultStr;
        } else {
            return "";
        }
    }

    function getMemberValue(memberID) {
        var memberNodes = $(xmldom).find("struct > member"), //
            htm = [], i, membersName, HelpTips, helpValue = "";

        for (i = 0; i < memberNodes.length; i += 1) {
            if (memberID === $(memberNodes[i]).attr("id")) {
                HelpTips = $(memberNodes[i]).children(lan);
                helpValue = $(HelpTips).text();
                break;
            }
        }
        return $.trim(helpValue);
    }

    //总帮助
    function all() {
        if (!xmldom) {
            xmldom = init();
            initVars();
        }
        return getAllStruct();
    }

    function get_structNode(structID) {
        var j = 0, id = "", structs = $(xmldom).find("root > struct");
        for (j = 0, len = structs.length; j < len; j += 1) {
            id = $(structs[j]).attr("id");
            if (id === structID) {
                return structs[j];
            }
        }
    }

    function getStruct(structID) {
        var htm = [], i = 0, //
            struct = get_structNode(structID), //
            members = $(struct).children(), //
            structDesc = localDB.T_search("c_param", "StructID", structID);
        if (structDesc.length === 0) {
            return "";
        }

        for (i = 0, len = members.length; i < len; i += 1) {
            var memberID = $(members[i]).attr("id"), memberName = "", //
                HelpTips = $(members[i]).children(lan), //
                helpValue = $(HelpTips).text();

            if (memberID !== null) {
                if ($.trim(helpValue) !== "") {
                    memberName = structDesc[i][showMemberNameIndex];
                    if ($.trim(memberName) === '') {
                        memberName = structDesc[i][memberNameIndex];
                    }
                    htm.push("<label id='Tips_" + memberID + //
                        "' onmouseover='tr_over_help(this)' onmouseout='tr_out_help(this)' ><b>" + //
                        memberName + ":</b>" + helpValue + "</label><br/>");
                }
            }
        }

        return htm.join("");
    }

    function getAllStruct() {
        var structs = $(xmldom).find("root > struct"), //
            htm = [], i, iLen = structs.length, //
            structID, structName, structDesc;

        for (i = 0; i < iLen; i += 1) {
            structID = $(structs[i]).attr("id");
            structDesc = localDB.T_search("c_param", "StructID", structID);

            if (structDesc.length > 0) {
                structName = structDesc[0][showStructNameIndex];
                if (structName === "") {
                    structName = structDesc[0][structNameIndex];
                }
                htm.push("<div class='infoTitle'><a href='javascript:void(0)' structID='" + structID + //
                    "' onclick='openAndClose(this)' state='close'>" + structName + "</a></div>");
                htm.push('<div class="helpAll" id="' + structID + '"></div>');
            }
        }
        return htm.join("");
    }

    return {
        get: get,
        all: all,
        getStruct: getStruct
    };
}());

/**
 * 读取xm/p-relate.xml文件，解析并执行其中参数依赖规则
 * 2013.03.12
 */

(function () {
    var g_XMLRoot = null, has_change = false, EventObj = {};

    /* class  RELATION */
    RELATION = function () {
        has_change = false;
    };
    RELATION.prototype = {
        /* public interface */
        isChanged: function () {
            return has_change;
        },
        /*灰色显示整个结构体*/
        disShow: function (structObj_in) {
            var structObj = top.objectClone(structObj_in);
            var WebTypeIndex = top.c_paramRowIndex.WebType;
            structDesc = structObj.structDesc;
            for (var m = 0; m < structDesc.length; m += 1) {
                if (structDesc[m][WebTypeIndex] != -1)
                    structDesc[m][WebTypeIndex] = change("d", structDesc[m][WebTypeIndex]);
            }

            structObj.structDesc = structDesc;
            return structObj;
        },

        update: function (structObj_in) {
            has_change = false;

            var structObj = top.objectClone(structObj_in), //

                structDesc = structObj.structDesc, //
                StructIDIndex = top.c_paramRowIndex.StructID, //
                WebTypeIndex = top.c_paramRowIndex.WebType, //
                MemberIDIndex = top.c_paramRowIndex.MemberID, //
                structid = structObj.structDesc[0][StructIDIndex], //
                relate_group = null, relate_rules = [];

            //获取所有的relate-rule，存数组
            relate_group = find_relate_group(structid);
            if (relate_group === null || $(relate_group).attr("type") === 'postProcess') {
                return structObj;
            }
            relate_rules = $(relate_group).children();
            if (!relate_rules || relate_rules.length === 0) {
                return structObj;
            }

            /*遍历每条relate-rule，根据keyMemberID，传入当前值，
             * 判断匹配哪条rule,执行该rule
             */
            var ruleValue = null, keywords = [], keywordValues = [], rules = [], //
                i = 0, len = 0, j = 0, innerLen = 0, subMemberID, //
                values, reg_exp, msg, k = 0, m = 0;
            for (i = 0, len = relate_rules.length; i < len; i += 1) {
                keywords = $(relate_rules[i]).attr('keyMemberID');
                keywords = parser(keywords);
                keywordValues = top.Struct.getValuesByMemberID(structObj, keywords);

                rules = $(relate_rules[i]).children();
                ruleValue = null;
                for (j = 0, innerLen = rules.length; j < innerLen; j += 1) {
                    ruleValue = $(rules[j]).attr('key-value');
                    ruleValue = parser(ruleValue);
                    if (compare(keywordValues, ruleValue)) {
                        subMemberID = parser($(rules[j]).attr('subMemberID'));
                        values = parser($(rules[j]).attr('action'));
                        reg_exp = parser($(rules[j]).attr('reg-exp'));
                        msg = parser($(rules[j]).attr('msg'));

                        if (subMemberID.length !== values.length) {
                            break;
                        }

                        for (k = 0; k < subMemberID.length; k += 1) {
                            for (m = 0; m < structDesc.length; m += 1) {
                                if (subMemberID[k] === structDesc[m][MemberIDIndex]) {
                                    structDesc[m][WebTypeIndex] = change(values[k], structDesc[m][WebTypeIndex]);
                                    break;
                                }
                            }
                        }
                        has_change = true;
                        break;
                    }
                }
            }

            structObj.structDesc = structDesc;
            return structObj;
        },
        delayEvent: function (id, j$) {

            EventObj.structid = id;
            EventObj.j$ = j$;

            //获取所有的relate-rule，存数组

            relate_group = find_relate_group(id);

            if (relate_group === null || $(relate_group).attr("type") !== 'postProcess') {
                return 0;
            }

            relate_rules = $(relate_group).children();
            if (!relate_rules || relate_rules.length === 0) {
                return 0;
            }

            var i = 0, j = 0, keyMemberIDs, selectId;
            for (i = 0; i < relate_rules.length; i += 1) {
                keyMemberIDs = parser($(relate_rules).attr("keyMemberID"));
                for (j = 0; j < keyMemberIDs.length; j += 1) {
                    selectId = "#" + id + "_" + keyMemberIDs[j] + "_0";
                    j$(selectId).unbind('change', (this.preDoEvent)).bind('change', EventObj, (this.preDoEvent));
                }
            }

            setTimeout(doEvent, 500);
        },
        preDoEvent: function (obj) {
            //EventObj.structid = obj.structid;
            //EventObj.j$       = obj.j$;

            doEvent();
        }
    };

    /* private functions */

    /**
     * 延时变化响应
     */

    function doEvent() {
        var structObj = top.CurrentStructs.get(EventObj.structid);
        eventExec(structObj, EventObj);
    }

    /**
     * @param{String} structObj_in, 传入，当前结构体
     */

    function eventExec(structObj_in, EventObj) {
        var structObj = structObj_in, //

            structDesc = structObj.structDesc, //
            StructIDIndex = top.c_paramRowIndex.StructID, //
            WebTypeIndex = top.c_paramRowIndex.WebType, //
            MemberIDIndex = top.c_paramRowIndex.MemberID, //
            structid = structObj.structDesc[0][StructIDIndex], //
            relate_group = null, relate_rules = [];

        //获取所有的relate-rule，存数组
        relate_group = find_relate_group(structid);
        if (relate_group === null || $(relate_group).attr("type") !== 'postProcess') {
            return 0;
        }
        relate_rules = $(relate_group).children();
        if (!relate_rules || relate_rules.length === 0) {
            return 0;
        }

        /*遍历每条relate-rule，根据keyMemberID，传入当前值，
         *判断匹配哪条rule,执行该rule
         */
        var ruleValue = null, keywords = [], keywordValues = [], rules = [], //
            i = 0, len = 0, j = 0, innerLen = 0, subMemberID, //
            values, reg_exp, msg, k = 0, m = 0;
        for (i = 0, len = relate_rules.length; i < len; i += 1) {
            keywords = $(relate_rules[i]).attr('keyMemberID');
            keywords = parser(keywords);
            keywordValues = top.Struct.getValuesByMemberID(structObj, keywords);

            rules = $(relate_rules[i]).children();
            ruleValue = null;
            for (j = 0, innerLen = rules.length; j < innerLen; j += 1) {
                ruleValue = $(rules[j]).attr('key-value');
                ruleValue = parser(ruleValue);
                if (compare(keywordValues, ruleValue)) {
                    subMemberID = parser($(rules[j]).attr('subMemberID'));
                    values = parser($(rules[j]).attr('action'));
                    reg_exp = parser($(rules[j]).attr('reg-exp'));
                    msg = parser($(rules[j]).attr('msg'));

                    if (subMemberID.length !== values.length) {
                        break;
                    }

                    ///////////////////////////////////////////////////
                    var selectid = "";
                    for (k = 0; k < subMemberID.length; k += 1) {
                        selectid = "#" + EventObj.structid + "_" + subMemberID[k] + "_0";

                        switch (values[k]) {
                            case 'e':
                                EventObj.j$(selectid).parent().parent().show();
                                EventObj.j$(EventObj.j$(selectid).children()[0]).removeAttr("disabled");
                                //缺少背景控制
                                break;
                            case 'd':
                                EventObj.j$(selectid).parent().parent().show();
                                EventObj.j$(EventObj.j$(selectid).children()[0]).attr({
                                    disabled: "disabled",
                                    style: "height:20px;vertical-align:middle;;background:#ffffff;opacity:0.4;filter:alpha(opacity=50);"
                                });
                                break;
                            case 'h':
                                EventObj.j$(selectid).parent().parent().hide();
                                //缺少背景控制
                                break;
                            default:
                        }
                    }
                    /////////////////////////////////////////////////////
                    break;
                }
            }
        }

        return 1;
    }

    /**
     * @param{String} action, 变化动作,即参数的目标状态,取值 d/e/h,分别对应:disable,enable,hide
     * @param{String} oType, 原始webType值
     */
    function change(action, oType) {
        oType = window.parseInt(oType, 10);

        if (action === 'd') {
            return WebTypeObj.toDisable(oType);
        } else if (action === 'e') {
            return WebTypeObj.toEnable(oType);
        } else if (action === 'h') {
            return -1;
        }

        return oType;
    }

    /**
     * 比较两数组是否全等
     */
    function compare(actualArr, expectedArr) {
        if (actualArr.length !== expectedArr.length) {
            return false;
        }

        var i = 0, len = 0;
        for (i = 0, len = actualArr.length; i < len; i += 1) {
            if ((actualArr[i] !== expectedArr[i]) && (expectedArr[i] !== "any")) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取当前struct对应的relate-group,返回DOM，or null on error
     */
    function find_relate_group(structid) {
        var groups = get_relate_groups(), id = "", i = 0, len = 0;
        if (!groups || groups.length === 0) {
            return null;
        }

        for (i = 0, len = groups.length; i < len; i += 1) {
            id = parser($(groups[i]).attr("structid"));
            if (id[0] === structid) {
                return groups[i];
            }
        }
        return null;
    }

    /**
     * 获取所有的 relate-group，返回数组
     */
    function get_relate_groups() {
        if (g_XMLRoot === null) {
            g_XMLRoot = get_xmlDoc();
            if (g_XMLRoot === null) {
                return [];
            }
        }

        return $(g_XMLRoot).find("relate-container > relate-group");
    }

    /**
     * 将此结构：['4600501','4600502']转换成数组
     */
    function parser(format_data) {
        try {
            return eval(format_data);
        } catch (e) {
            return [];
        }
    }

    /**
     *  加载xml ,return DOM object, or null on error.
     */
    function get_xmlDoc() {
        var url = "xml/p-relate.xml?r=" + top.VALIDATION_STRING, root = null;

        $.ajax({
            type: "post",
            url: "xml/p-relate.xml?r=" + top.VALIDATION_STRING,
            async: false,
            dataType: "xml",
            success: function (data, textStatues) {
                root = data;
            },
            error: function () {
                throw new Error("get xml error");
            }
        });
        return root;
    }

}());

/**
 *  5min无操作自动退出 ,返回一个setInterval定时检查是否有操作的timerid
 */
var globalShiftBtn = false, globalCtrlBtn = false;

function bindGlobalEvent() {
    var idelControl = {}, preDate = new Date(), childIframe = null, childIframe2 = null;
    idelControl.enable = false;

    idelControl.checktime = function () {
        var nowDate = new Date(), offset = nowDate - preDate;
        //5 mins
        if (offset > 5 * 60 * 1000 && idelControl.enable) {
            System.logout(1);
        }
    };

    idelControl.mmove = function () {
        preDate = new Date();
    };

    idelControl.keyDown = function (event) {
        preDate = new Date();
        var evt = event || window.event;
        if (evt) {
            if (evt.shiftKey) {//shiftKey
                globalShiftBtn = true;
            } else if (evt.ctrlKey) {//ctrlKey
                globalCtrlBtn = true;
            }
        }
    };

    idelControl.keyUp = function (event) {
        var evt = event || window.event;
        if (evt) {
            if (evt.shiftKey) {//shiftKey
                globalShiftBtn = false;
            } else if (evt.ctrlKey) {//ctrlKey
                globalCtrlBtn = false;
            }
        }
    };

    childIframe = document.getElementById("contentMainFrame");
    $(childIframe).load(function () {
        $(window.frames["mainFrame"].document).keydown(idelControl.keyDown);
        $(window.frames["mainFrame"].document).keyup(idelControl.keyUp);
        $(window.frames["mainFrame"].document).mousemove(idelControl.mmove);
    });

    childIframe2 = document.getElementById("wlan_guide_iframe");
    $(childIframe2).load(function () {
        $(window.frames["iframe_guide"].document).keydown(idelControl.keyDown);
        $(window.frames["iframe_guide"].document).keyup(idelControl.keyUp);
        $(window.frames["iframe_guide"].document).mousemove(idelControl.mmove);
    });

    $(document).keydown(idelControl.keyDown);
    $(document).keyup(idelControl.keyUp);
    $(document).mousemove(idelControl.mmove);

    return setInterval(idelControl.checktime, 3000);
}

/**
 * 参数校验函数
 */
function valueCheck(structObj, e_tips) {
    var structDesc = structObj.structDesc, //
        StructIDIndex = top.c_paramRowIndex.StructID, //
        MemberIDIndex = top.c_paramRowIndex.MemberID, //
        WebTypeIndex = top.c_paramRowIndex.WebType, //
        RegexIndex = top.c_paramRowIndex.Regex, //
        MemberNameIndex = top.c_paramRowIndex.MemberName, //
        MemberCnNameIndex = top.c_paramRowIndex.MemberCnName, //
        StructNameIndex = top.c_paramRowIndex.StructName, //
        IsPrimaryKeyIndex = top.c_paramRowIndex.IsPrimaryKey, //
        ValueTypeIndex = top.c_paramRowIndex.ValueType, //
        LevelIndex = top.c_paramRowIndex.Level, //
        vIt = 0, len = 0, descIndex = 0, webType = -1, dbReg = "", fTest = true, testVal = "", //
        fun = "", paramsStart = 0, params = [], vals = [], //
        chObj = {}, checkerObj = {}, valueList = [], CurrentItem = "", i = 0, j = 0, //
        tipsName = "", Level = "", range = 0, idNameReg = "", idNameResult = false;

    if (!structObj.sLength) {// if undefined
        structObj.sLength = structObj.structDesc.length;
    }

    /*校验 begin*/
    for (vIt = 0, len = structObj.name_val.length; vIt < len; vIt += 1) {
        descIndex = vIt % structObj.sLength;

        if (!structObj.name_val[vIt].changed) {
            /* 没有改变值的不进行校验 */
            continue;
        }

        webType = window.parseInt(structDesc[descIndex][WebTypeIndex], 10);
        if (webType === 2 || webType === 12 || webType === 102) {// 数组类型不在此校验校验
            continue;
        }

        dbReg = $.trim(Transfer.parseDbColumn(structDesc[descIndex][RegexIndex]));

        if (dbReg !== "" && dbReg !== "*") {
            fTest = true;
            testVal = $.trim(structObj.name_val[vIt].val);
            /**
             * 定义数据库正则表达式格式，以dbReg的开头部分区分:
             * A:(default)原生正则表达式；
             * B:自定义校验表达式(冯工开发)
             * C:函数，例如:"C:isIP"或"C:isInTheSameNet(WANIP,WANGateway,WANMask)"
             * 当指定的函数不带参数时，传入当前参数输入值；
             * 当指定的函数带参数说明，参数名称需与所在结构体参数名称相同，
             * 只支持传入当前结构体的参数，所调用函数需支持以一个数组形式将多个参数传入。
             * D:自定义校验表达式#{maxLength:128,maxItems:15,minItems:0,nullEnable:true,unique:true},
             * 例如：D:[9400,9600]||[10050,10125]#{maxLength:128,maxItems:15,minItems:0,nullEnable:true,unique:true}
             */
            try {
                if (dbReg.indexOf("B:") === 0) {
                    dbReg = dbReg.substring(2, dbReg.length);
                    fTest = ValidCheck.IsValid(dbReg, testVal);
                } else if (dbReg.indexOf("C:") === 0) {
                    fun = dbReg.substring(2, dbReg.length);
                    paramsStart = fun.indexOf("(");
                    if (paramsStart > 0) {//多参数函数调用
                        params = fun.substring(paramsStart + 1, fun.length - 1);
                        fun = fun.substring(0, paramsStart);

                        idNameReg = new RegExp("^(\\d{1,},{0,1})+$");
                        //判断是memberId还是memberName
                        idNameResult = idNameReg.test(params);
                        params = params.split(",");
                        if (idNameResult === false) {
                            vals = Struct.getValuesByMemberName(structObj, params);
                        } else {
                            vals = Struct.getValuesByMemberID(structObj, params);
                        }

                        fTest = window[fun](vals);
                    } else {//单参数函数调用
                        fTest = window[fun](testVal);
                    }
                } else if (dbReg.indexOf("D:") === 0) {
                    valueList = [];
                    dbReg = $.trim(dbReg);
                    chObj = dbReg.substring(2, dbReg.length);
                    chObj = chObj.split('#');

                    dbReg = $.trim(chObj[0]);
                    checkerObj = eval('(' + $.trim(chObj[1]) + ')');

                    if (testVal.length > checkerObj.maxLength) {
                        /* 总长度 */
                        fTest = false;
                    } else if (testVal.length === 0) {
                        /* 是否可以为空 */
                        if (!checkerObj.nullEnable) {
                            fTest = false;
                        } else {
                            fTest = true;
                        }
                    } else {
                        valueList = testVal.split(',');

                        if (valueList.length < checkerObj.minItems) {
                            /* 最小项数限制  */
                            fTest = false;
                        } else if (checkerObj.maxItems !== -1 && valueList.length > checkerObj.maxItems) {
                            /* 最大项数限制,checkerObj.maxItems ==-1 为无最大项限制 */
                            fTest = false;
                        } else {
                            CurrentItem = "";
                            for (i = 0; i < valueList.length; i += 1) {
                                valueList[i] = $.trim(valueList[i]);
                            }

                            // 依次校验每个取值的合法性
                            for (i = 0; i < valueList.length; i += 1) {
                                CurrentItem = valueList[i];
                                if (checkerObj.unique) {
                                    for (j = i + 1; j < valueList.length; j += 1) {
                                        if (CurrentItem === valueList[j]) {
                                            fTest = false;
                                            break;
                                        }
                                    }
                                    //唯一性校验不过
                                    if (!fTest) {
                                        break;
                                    }
                                }

                                /* 取值范围 */
                                fTest = ValidCheck.IsValid(dbReg, CurrentItem);
                                if (!fTest) {
                                    break;
                                }
                            }
                        }
                    }

                    /* 校验成功 */
                    if (fTest) {
                        var ret = "";
                        for (i = 0; i < valueList.length; i += 1) {
                            ret += valueList[i] + ",";
                        }
                        testVal = ret.substring(0, ret.length - 1);
                    }
                } else {
                    // 如果有A:开头，去掉
                    if (dbReg.indexOf("A:") === 0) {
                        dbReg = dbReg.substring(2, dbReg.length);
                    }
                    var Regex = new RegExp(dbReg.replace(/\\\\/g, "\\"), "g"), //
                        ValueType = structDesc[descIndex][ValueTypeIndex].toLowerCase(), //
                        SHI_LIU_REG, tmpVal, SHI_LIU_REG_test;
                    if (ValueType.indexOf("int") !== -1) {
                        if (testVal.toString().indexOf("0x") === 0 || testVal.toString().indexOf("0X") === 0) {
                            SHI_LIU_REG = /^[a-fA-F0-9]+$/;
                            tmpVal = testVal.substring(2, testVal.length);
                            SHI_LIU_REG_test = SHI_LIU_REG.test(tmpVal);
                            if (SHI_LIU_REG_test) {
                                testVal = window.parseInt(testVal, 16);
                            }
                        }
                    }
                    fTest = Regex.test(testVal);
                }
            } catch (e) {
                fTest = true;
            }

            if (!fTest) {
                Level = Transfer.parseDbColumn(structDesc[descIndex][LevelIndex]);
                range = Level.split('|');

                if (Language === "EN") {
                    tipsName = structDesc[descIndex][MemberNameIndex];
                    if (range.length >= 7 && range[6] !== '') {
                        range = "<br>" + range[6];
                    } else {
                        range = '';
                    }
                } else {
                    tipsName = (structDesc[descIndex][MemberCnNameIndex] === "") ? //
                        structDesc[descIndex][MemberNameIndex] : structDesc[descIndex][MemberCnNameIndex];
                    if (range.length >= 2 && range[1] !== '') {
                        range = "<br>" + range[1];
                    } else {
                        range = '';
                    }
                }

                tipsName = "[" + tipsName + "] ";
                if (typeof (e_tips) === 'undefined' || e_tips === null) {
                    Modal.open(top.T.AlertInfo.InputError, tipsName + top.T.AlertInfo.InputAgain + range, "error");
                } else {
                    Modal.open(top.T.AlertInfo.InputError, e_tips + tipsName + top.T.AlertInfo.InputAgain + range, "error");
                }
                return false;
            }

            /* 去除前后空格  */
            structObj.name_val[vIt].val = $.trim(testVal);
        }
    }
    /*校验 end*/
    return true;
}

// 全局变量对象
var G = {
    PageRows: 16 // 多实例分页显示，一页最大显示行数
};
/**
 * 保存当前页面处理的所有StructObj：
 * 封装了通过这些StructObj对页面赋值，页面参数值更新到StructObj，StructObj参数值保存入数据库；
 * StructObj的刷新；提供push、get一个StructObj的接口；
 * 对于多实例，提供添加、删除操作；
 */
var CurrentStructs = (function () {
    // 当前操作的结构体数组，[[structID,structObj],[structID,structObj]]
    var COperateStructs = [];

    function init() {
        COperateStructs = [];
    }

    function push(structObj) {
        if (structObj.structDesc.length < 1) {
            //alert("CurrentStructs push() param error.");
            return;
        }

        var structID = structObj.structDesc[0][top.c_paramRowIndex.StructID], //
            i = 0, iLen = COperateStructs.length;
        for (i = 0; i < iLen; i += 1) {
            if (COperateStructs[i][0] === structID) {
                COperateStructs[i][1] = structObj;
                break;
            }
        }

        //未存在的结构体
        if (i === iLen) {
            COperateStructs.push([structID, structObj]);
        }
    }

    /**
     * @param{String} [structID],if undefined, return the first one
     */
    function get(structID) {
        if (typeof (structID) === "undefined") {
            return COperateStructs[0][1];
        } else {
            var i = 0, len = COperateStructs.length;
            for (i = 0; i < len; i += 1) {
                if (COperateStructs[i][0] === structID) {
                    return COperateStructs[i][1];
                }
            }
        }
        return null;
    }

    function del(structID) {
        var i = 0, iLen = COperateStructs.length;

        if (typeof (structID) === "undefined") {
            return;
        } else {
            for (i = 0; i < iLen; i += 1) {
                if (COperateStructs[i][0] === structID) {
                    COperateStructs.splice(i, 1);
                    break;
                }
            }

        }
        return null;
    }

    /**
     * 为页面表格赋值
     * @param{Object} $, 页面的$对象。
     * @param{String} [structID], if undefined, evaluation all
     * @param{Number} [page] optional, 多实例分页显示，分页赋值,default : 1
     */
    function evaluation($, structID, page) {
        var i = 0, len = COperateStructs.length;
        if (structID) {
            for (i = 0; i < len; i += 1) {
                if (COperateStructs[i][0] === structID) {
                    doEvaluation($, COperateStructs[i][1], page);
                    break;
                }
            }
        } else {
            for (i = 0; i < len; i += 1) {
                doEvaluation($, COperateStructs[i][1], page);
            }
        }
    }

    /**
     * 赋值
     * @param{Object} structObj
     */
    function doEvaluation($, structObj, page) {
        var i = 0, len = 0, descIndex = 0, descLen = structObj.structDesc.length, //
            divID = "", valueType = "", k = 0, kLen = 0, //
            obj = {}, value, checkboxs = [], isMult = Struct.isMulInstance(structObj.structDesc), //
            rows = 0, MemberIDIndex = top.c_paramRowIndex.MemberID, //
            StructIDIndex = top.c_paramRowIndex.StructID, //
            tmpArr = {}, selectNames = [], selectVals = [], //
            TypeDescIndex = top.c_paramRowIndex.TypeDesc, //
            evalLen = structObj.name_val.length;

        if (isMult) {
            if (typeof (page) === 'undefined') {
                page = 1;
            }
            i = (page - 1) * descLen * G.PageRows;
            evalLen = i + descLen * G.PageRows;
            if (evalLen > structObj.name_val.length) {
                evalLen = structObj.name_val.length;
            }

            rows = (page - 1) * G.PageRows;
        }

        for (len = evalLen; i < len; i += 1) {
            //多实例中desc的数组长度和name_val长度不一致
            descIndex = i % descLen;
            divID = "#" + structObj.structDesc[descIndex][StructIDIndex] + "_" + //
                structObj.structDesc[descIndex][MemberIDIndex] + "_";
            if (isMult) {
                divID += rows.toString();
                if (((i + 1) % structObj.sLength) === 0) {
                    rows += 1;
                }
            } else {
                divID += "0";
            }

            valueType = window.parseInt($(divID).attr("memberType"), 10);
            obj = $(divID).children()[0];
            if (!obj) {
                continue;
            }
            switch (valueType) {
                case -1:
                    break;
                // 1、11
                case 1:
                case 11:
                    // 赋值时不区别大小写
                    value = structObj.name_val[i].val.toLowerCase();
                    tmpArr = $(obj).children('option');
                    for (k = 0, kLen = tmpArr.length; k < kLen; k += 1) {
                        if ($(tmpArr[k]).attr("value").toLowerCase() === value) {
                            value = $(tmpArr[k]).attr("value");
                            $(obj).next().html($(tmpArr[k]).html());
                            break;
                        }
                    }
                    $(obj).val(value);
                    break;
                // 2、12
                case 2:
                case 12:
                    $(obj).attr("proto", structObj.name_val[i].val);
                    value = strToArr(structObj.name_val[i].val);
                    $(obj).val(value);
                    break;
                //4、14
                case 4:
                    checkboxs = $("input[name='" + structObj.name_val[i].name + "']").parent().children();
                    value = structObj.name_val[i].val.split(",");
                    for (k = 0, kLen = value.length; k < kLen; k += 1) {
                        for (var m = 0; m < checkboxs.length; m += 1) {
                            if (!isNaN(parseInt(value[k], 10))) {
                                if (parseInt(value[k], 10) === parseInt($(checkboxs[m]).attr("value"), 10)) {
                                    $(checkboxs[m]).attr("checked", true);
                                    break;
                                }
                            } else {
                                if ($.trim(value[k]) === $.trim($(checkboxs[m]).attr("value"))) {
                                    $(checkboxs[m]).attr("checked", true);
                                    break;
                                }
                            }

                        }
                    }
                    break;
                case 14:
                    checkboxs = $("input[name='" + structObj.name_val[i].name + "']").parent().children();
                    value = structObj.name_val[i].val.split(",");
                    for (k = 0, kLen = value.length; k < kLen; k += 1) {
                        for (var m = 0; m < checkboxs.length; m += 1) {
                            if (parseInt(value[k], 10) === parseInt($(checkboxs[m]).attr("value"), 10)) {
                                $(checkboxs[m]).attr("checked", true);
                                break;
                            }
                        }
                    }
                    break;
                //5、15
                case 5:
                case 15:
                    $(obj).attr("proto", structObj.name_val[i].val);
                    break;
                //6 、16
                case 6:
                case 16:
                    if (structObj.name_val[i].val === "1") {
                        $(obj).attr("checked", true);
                    }
                    break;
                case 7:
                    // <a>some link</a>  不用赋值
                    break;
                case 8:
                    value = $.trim(structObj.name_val[i].val);
                    try {
                        tmpArr = top.Transfer.wtListParser(structObj.structDesc[i][TypeDescIndex], //
                            structObj.structDesc[i][MemberIDIndex]);
                        selectNames = tmpArr.selectNames;
                        selectVals = tmpArr.selectVals;

                        if (selectNames.length === 0 || selectNames.length !== selectVals.length) {
                            $(obj).text(value);
                        } else {
                            for (k = 0; k < selectVals.length; k += 1) {
                                if (value === $.trim(selectVals[k])) {
                                    $(obj).text(selectNames[k]);
                                    break;
                                }
                            }
                            if (k === selectVals.length) {
                                $(obj).text(value);
                            }
                        }
                    } catch (e) {
                        $(obj).text(value);
                    }
                    break;
                case 9:
                    value = structObj.name_val[i].val;
                    $(obj).attr("proto", value);
                    $(obj).val("bitMap(" + value + ")");
                    break;
                case 20:
                    // 赋值时不区别大小写
                    value = structObj.name_val[i].val.toLowerCase();
                    tmpArr = $(obj).children('option');
                    for (k = 0, kLen = tmpArr.length; k < kLen; k += 1) {
                        if ($(tmpArr[k]).attr("value").toLowerCase() === value) {
                            value = $(tmpArr[k]).attr("value");
                            break;
                        }
                    }
                    $(obj).val(value);
                    break;
                case 10:
                    $(obj).html(structObj.name_val[i].val);
                    break;
                default:
                    /* 尾数是0,3 */
                    $(obj).val(structObj.name_val[i].val);
                    break;
            }
        }
    }

    function strToArr(recive_str) {
        var pat_a = /\d+/g, valueArr = recive_str.match(pat_a), i = 0, len = 0, ret = "";
        if (valueArr && valueArr.length > 0) {
            for (i = 0, len = valueArr.length; i < len; i += 1) {
                ret += "a[" + i + "]=" + valueArr[i] + ",";
            }
        } else {
            ret = ",";
        }

        return ret.substring(0, ret.length - 1);
    }

    function update(node, structID, memberName, value, cid) {
        var i = 0, len = COperateStructs.length, structObj = {}, //
            structLen = 0, j = 0, jLen = 0;
        if (typeof (cid) === "undefined") {
            cid = "0";
        }
        cid = window.parseInt(cid, 10);

        for (i = 0; i < len; i += 1) {
            if (structID === COperateStructs[i][0]) {
                structObj = COperateStructs[i][1];
                //多实例||单实例
                structLen = structObj.sLength || 0;
                jLen = structObj.sLength || structObj.name_val.length;
                for (j = cid * structLen, jLen = j + jLen; j < jLen; j += 1) {
                    if (structObj.name_val[j].name === memberName) {
                        if (structObj.name_val[j].val === value) {
                            return;
                        } else {
                            structObj.name_val[j].changed = true;
                            structObj.name_val[j].val = value;
                            if ($(node).is('input') && $(node).attr("type") !== "button") {
                                //$(node).addClass("textInput textInputUpdate");
                            }
                            $(node).data('changed', true);
                            break;
                        }
                    }
                }
                break;
            }
        }
    }

    /**
     * @param{String} [structID], if undefined ,save all
     * 当一个页面多个结构体，多个保存按钮时，可以选择单独保存
     */
    function save(structID) {
        // 获取本次需要保持的结构体数组，含未拆分的混合结构体
        var saveStructs = getSaveStructs(structID), i = 0, iLen = saveStructs.length, //
            dbStructs = [], cmds = [], ack = null, SysFlag;
        //needRebootMembers = [];

        // 对所有将保持的结构体做校验,如果有一个校验失败，则终止保存操作, valueCheck()内部做了出错提示
        for (i = 0; i < iLen; i += 1) {
            if (!valueCheck(saveStructs[i])) {
                return false;
            }
        }

        // 校验通过, 逆向拆分混合结构体，得到所有对应于数据库的保存结构体数组
        // 拆分混合结构体必须在校验通过后，因为混合结构体校验时可能跨结构体
        for (i = 0; i < iLen; i += 1) {
            if (saveStructs[i].matrix) {
                dbStructs = dbStructs.concat(MatrixStruct.set());
            } else {
                dbStructs.push(saveStructs[i]);
            }
        }

        // 获取保存命令数组
        for (i = 0, iLen = dbStructs.length; i < iLen; i += 1) {
            cmds = cmds.concat(getSaveCmd(dbStructs[i]));
        }
        // 没有修改
        if (cmds.length === 0) {
            Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.ParamValueNoChangeInfo, "ok");
            return true;
        }

        // 执行保存命令
        ack = Struct.setStructsByCmds(cmds);
        if (ack.result === "000") {
            // 获取重启生效参数需要在重置changed属性resetChangedAttr()前
            //=needRebootMembers = getNeedRebootMembers(saveStructs);
            SysFlag = getSysFlag(saveStructs);
            Priority = 3;
            if (SysFlag === 0) {
                Modal.open(top.T.AlertInfo.SaveSuccess, top.T.AlertInfo.AutoReboot, "ok");
                setTimeout(function () {
                    top.Progress.reBooting();
                }, 2000);
            } else if (Priority === -1) {
                if (SysFlag === 1) {
                    Priority = 1;
                    //Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.SaveSuccess + ',' + top.T.AlertInfo.NeedReboot, "reboot");
                    Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.SaveSuccess + ',' + top.T.AlertInfo.NeedReboot, "ok");
                } else if (SysFlag === 2) {
                    Priority = 2;
                    //Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.SaveSuccess + ',' + top.T.AlertInfo.NeedReActivate, "reactivate");
                    Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.SaveSuccess + ',' + top.T.AlertInfo.NeedReActivate, "ok");
                } else if (SysFlag === 3) {
                    Priority = 3;
                    //Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.SaveSuccess + ',' + top.T.AlertInfo.DynamicEffect, "DynamicEffect");
                    Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.SaveSuccess + ',' + top.T.AlertInfo.DynamicEffect, "ok");
                } else {
                    Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.SaveSuccess, "ok");
                }
            } else if (Priority === 1 || SysFlag === 1) {
                Priority = 1;
                //Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.SaveSuccess + ',' + top.T.AlertInfo.NeedReboot, "reboot");
                Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.SaveSuccess + ',' + top.T.AlertInfo.NeedReboot, "ok");
            } else if (Priority === 2 && SysFlag !== 1 || Priority !== 1 && SysFlag === 2) {
                Priority = 2;
                //Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.SaveSuccess + ',' + top.T.AlertInfo.NeedReActivate, "reactivate");
                Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.SaveSuccess + ',' + top.T.AlertInfo.NeedReActivate, "ok");
            } else if (Priority === 3 && SysFlag === 3) {
                Priority = 3;
                //Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.SaveSuccess + ',' + top.T.AlertInfo.DynamicEffect, "DynamicEffect");
                Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.SaveSuccess + ',' + top.T.AlertInfo.DynamicEffect, "ok");
            } else {
                Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.SaveSuccess, "ok");
            }

            // 重置changed需要传入的是saveStructs，因为它们是COperateStructs里面的引用
            resetChangedAttr(saveStructs);
            return true;
        } else if (ack.result === "004") {
            Modal.open(top.T.AlertInfo.OperationFail, ack.hint, "error");
            return false;
        } else {
            Modal.open(top.T.AlertInfo.OperationFail, ack.protoContent, "error");
            return false;
        }
    }

    /**
     * 获取本次需要保存的结构体，含为拆分的混合结构体
     * @param{String}[structID], if undefined ,save all
     * @return{Array}saveStructs
     * @private
     */
    function getSaveStructs(structID) {
        //添加正则校验用于去掉多实例虚拟结构体（例如 77777Add）
        var saveStructs = [], i = 0, iLen = COperateStructs.length, reg = /^(\d)+Add$/;
        //处理混合结构体或者是设置向导
        if (typeof (structID) === "undefined") {
            for (i = 0; i < iLen; i += 1) {
                if (!reg.test(COperateStructs[i][0])) {
                    saveStructs.push(COperateStructs[i][1]);
                }
            }
            //处理单实例或者多实例
        } else {
            for (i = 0; i < iLen; i += 1) {
                if (COperateStructs[i][0] === structID) {
                    saveStructs.push(COperateStructs[i][1]);
                    break;
                }
            }
        }

        return saveStructs;
    }

    /**
     * 查找本次保存中需要重启生效的参数
     * @param{Array}saveStructs
     * @return{Array} mems
     * @private
     */
    function getNeedRebootMembers(saveStructs) {
        var mems = [], SetStatusIndex = top.c_paramRowIndex.SetStatus;
        // 旧版本没有该参数
        if (SetStatusIndex === -1) {
            return [];
        }

        var i = 0, iLen = saveStructs.length, j = 0, jLen = 0, SetStatus = 0;
        for (i = 0; i < iLen; i += 1) {
            for (j = 0, jLen = saveStructs[i].name_val.length; j < jLen; j += 1) {
                if (saveStructs[i].name_val[j].changed) {
                    SetStatus = saveStructs[i].structDesc[j % (saveStructs[i].structDesc.length)][SetStatusIndex];
                    SetStatus = parseInt(SetStatus, 10);
                    if (SetStatus === 1) {
                        mems.push(saveStructs[i].name_val[j].name);
                    }
                }
            }
        }
        return mems;
    }

    /**
     *返回本次保存系统操作的级别 1.代表重启，2代表重激活，3.动态生效,0 自动重启
     *
     */
    function getSysFlag(saveStructs) {
        var Status_flag, StatusIndex = top.c_paramRowIndex.SetStatus, reboot_mems = [], reactivate_mems = [],
            dynamic_mems = [], auto_reboot = [];
        if (StatusIndex === -1) {
            return [];
        }
        var i = 0, iLen = saveStructs.length, j = 0, jLen = 0, SetStatus = 0;
        for (i = 0; i < iLen; i += 1) {
            for (j = 0, jLen = saveStructs[i].name_val.length; j < jLen; j += 1) {
                if (saveStructs[i].name_val[j].changed) {
                    SetStatus = saveStructs[i].structDesc[j % (saveStructs[i].structDesc.length)][StatusIndex];
                    SetStatus = parseInt(SetStatus, 10);
                    if (SetStatus === 0) {
                        auto_reboot.push(saveStructs[i].name_val[j].name);
                    } else if (SetStatus === 1) {
                        reboot_mems.push(saveStructs[i].name_val[j].name);
                    } else if (SetStatus === 2) {
                        reactivate_mems.push(saveStructs[i].name_val[j].name);
                    } else if (SetStatus === 3) {
                        dynamic_mems.push(saveStructs[i].name_val[j].name);
                    }

                }
            }
        }
        if (auto_reboot.length !== 0) {
            Status_flag = 0;
        } else if (reboot_mems.length !== 0) {
            Status_flag = 1;
        } else if (reactivate_mems.length !== 0) {
            Status_flag = 2;
        } else if (dynamic_mems.length !== 0) {
            Status_flag = 3;
        }
        return Status_flag;
    }

    /**
     * 保存成功，重置已保存的结构体的成员changed属性为false
     * @param{Array}saveStructs CurrentStructs里面的结构体数组
     * @private
     */
    function resetChangedAttr(saveStructs) {
        var i = 0, iLen = saveStructs.length, j = 0, jLen = 0;
        for (i = 0; i < iLen; i += 1) {
            for (j = 0, jLen = saveStructs[i].name_val.length; j < jLen; j += 1) {
                saveStructs[i].name_val[j].changed = false;
            }
        }
    }

    /**
     * @return{Array} cmds:[]
     * @private
     */
    function getSaveCmd(structObj) {
        var structDesc = structObj.structDesc, descIndex = 0, descLen = structDesc.length, //
            i = 0, instanceCnt = 0, primaryKey = 0, //
            MemberNameIndex = top.c_paramRowIndex.MemberName, //
            StructNameIndex = top.c_paramRowIndex.StructName, //
            IsPrimaryKeyIndex = top.c_paramRowIndex.IsPrimaryKey, //
            vMemberName = [], vVal = [], primaryCnt = 0, k = 0, len = 0, cmd = [];

        if (Struct.isMulInstance(structDesc)) {
            //多实例保存，每个实例一条命令保存，带关键字
            instanceCnt = structObj.name_val.length / descLen;
            for (i = 0; i < instanceCnt; i += 1) {
                vMemberName = [];
                vVal = [];
                primaryCnt = 0;
                for (k = i * descLen, len = k + descLen; k < len; k += 1) {
                    descIndex = k % descLen;
                    primaryKey = window.parseInt(structDesc[descIndex][IsPrimaryKeyIndex], 10);
                    if (structObj.name_val[k].changed || primaryKey === 1) {
                        vMemberName.push(structDesc[descIndex][MemberNameIndex]);
                        vVal.push(structObj.name_val[k].val);
                        if (primaryKey === 1) {
                            primaryCnt += 1;
                        }
                    }
                }
                //保存一实例
                if (vMemberName.length > primaryCnt) {
                    cmd.push(CMDBuider.lmtCreateSetReq(structDesc[0][StructNameIndex], vMemberName, vVal));
                }
            }
        } else {
            //单实例保存，直接将所有changed=true的保存
            for (k = 0, len = structObj.name_val.length; k < len; k += 1) {
                if (structObj.name_val[k].changed) {
                    vMemberName.push(structDesc[k][MemberNameIndex]);
                    vVal.push(structObj.name_val[k].val);
                }
            }
            if (vMemberName.length > 0) {
                cmd.push(CMDBuider.lmtCreateSetReq(structDesc[0][StructNameIndex], vMemberName, vVal));
            }
        }

        return cmd;
    }

    /**
     * 更新 StructID对应的StructObj
     */
    function refresh(structID) {
        var i = 0, len = COperateStructs.length, structObj = {}, //
            structName = "", StructNameIndex = top.c_paramRowIndex.StructName;
        for (i = 0; i < len; i += 1) {
            if (COperateStructs[i][0] === structID) {
                structObj = COperateStructs[i][1];
                structName = structObj.structDesc[0][StructNameIndex];
                COperateStructs[i][1] = Struct.getStructByName(structName);
                break;
            }
        }
    }

    /**
     * 将COperateStructs中structID对应structObj的name_val初始化为空值
     */
    function name_valInit(structID) {
        var i = 0, j = 0, len = COperateStructs.length, structObj = {}, name_val = {
                changed: false,
                val: '',
                type: 'string',
                name: ''
            }, MemberNameIndex = top.c_paramRowIndex.MemberName, webTips = "", infos = [], uniqueFrag = 0, //
            IsPrimaryKeyIndex = top.c_paramRowIndex.IsPrimaryKey, //
            DefaultValueIndex = top.c_paramRowIndex.DefaultValue;
        for (i = 0; i < len; i += 1) {
            if (COperateStructs[i][0] === structID) {
                structObj = COperateStructs[i][1];
                structObj.name_val = [];
                for (j = 0; j < structObj.structDesc.length; j += 1) {
                    name_val.name = structObj.structDesc[j][MemberNameIndex];
                    //如果c_param表中有DefaultValue字段，则用DefaultValue初始化
                    if (DefaultValueIndex > 0) {
                        name_val.val = structObj.structDesc[j][DefaultValueIndex];
                    }
                    structObj.name_val.push(top.objectClone(name_val));

                    // 多实例唯一性标识
                    webTips = Transfer.parseDbColumn(structObj.structDesc[j][top.c_paramRowIndex.Level]);
                    infos = webTips.split('|');
                    if (infos.length >= 6 && infos[5].length >= 1) {
                        uniqueFrag = window.parseInt(infos[5], 10);
                    } else {
                        uniqueFrag = 0;
                    }

                    //将关键字的changed属性置为true，以便后面即使用户未修改也执行校验
                    if (window.parseInt(structObj.structDesc[j][IsPrimaryKeyIndex], 10) === 1 || //
                        uniqueFrag === 1) {
                        structObj.name_val[j].changed = true;
                    }
                }
                break;
            }
        }
    }

    /**
     * 将 COperateStructs 中标识为structID+"Add"对应的structObj取出，执行add命令
     * @param{String} structID,
     * @return{Boolean}
     */
    function instanceAdd(structID) {
        var i = 0, j = 0, len = COperateStructs.length, jLen = 0, structIDAdd = "", structObj = {}, //
            structName = "", memArr = [], valArr = [], cmd = "", ack = {}, //
            primaryKey = 0, IsPrimaryKeyIndex = top.c_paramRowIndex.IsPrimaryKey, //
            StructNameIndex = top.c_paramRowIndex.StructName;

        structIDAdd = structID + "Add";
        for (i = 0; i < len; i += 1) {
            if (COperateStructs[i][0] === structIDAdd) {
                structObj = COperateStructs[i][1];

                if (!valueCheck(structObj)) {
                    return;
                }

                structName = structObj.structDesc[0][StructNameIndex];
                for (j = 0, jLen = structObj.structDesc.length; j < jLen; j += 1) {

                    primaryKey = window.parseInt(structObj.structDesc[j][IsPrimaryKeyIndex], 10);
                    if (structObj.name_val[j].changed || primaryKey === 1) {
                        memArr.push(structObj.name_val[j].name);
                        valArr.push(structObj.name_val[j].val);
                    }
                }
                cmd = CMDBuider.lmtCreateAddReq(structName, memArr, valArr);
                ack = LMT.cmdAsyn(cmd);
                ack = LMT.parser(ack);

                if (ack.result === "000") {
                    if ("75330" != structID) {
                        Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.SaveSuccess, "ok");
                    } else {
                        Modal.delProgress();
                    }
                    name_valInit(structIDAdd);
                    return true;
                } else {
                    if (ack.result === "004") {
                        Modal.open(top.T.AlertInfo.OperationFail, ack.hint, "error");
                    } else {
                        Modal.open(top.T.AlertInfo.OperationFail, ack.protoContent, "error");
                    }
                }
                break;
            }
        }
        return false;
    }

    /**
     * 删除多实例的若干实例
     * @param{String} structID,
     * @param{Array} instanceIndexArr, 将要删除的实例的索引顺序
     * @return{Boolean}
     */
    function instanceDel(structID, instanceIndexArr) {
        var structName = "", memArr = [], vArr = [], structObj = {}, descIndex = 0, //
            descLen = 0, i = 0, len = 0, j = 0, jLen = 0, ack = null, errAck = null, //
            IsPrimaryKeyIndex = top.c_paramRowIndex.IsPrimaryKey, IsPrimaryKey = 0, //
            StructNameIndex = top.c_paramRowIndex.StructName;

        for (i = 0, len = COperateStructs.length; i < len; i += 1) {
            if (COperateStructs[i][0] === structID) {
                structObj = COperateStructs[i][1];
                break;
            }
        }
        structName = structObj.structDesc[0][StructNameIndex];
        descLen = structObj.structDesc.length;

        for (i = 0, len = instanceIndexArr.length; i < len; i += 1) {
            memArr = [];
            vArr = [];
            for (j = instanceIndexArr[i] * descLen, jLen = j + descLen; j < jLen; j += 1) {
                descIndex = j % descLen;
                if (window.parseInt(structObj.structDesc[descIndex][IsPrimaryKeyIndex], 10) === 1) {
                    memArr.push(structObj.name_val[j].name);
                    vArr.push(structObj.name_val[j].val);
                }
            }
            ack = Struct.deleteStruct(structName, memArr, vArr);

            if (ack.result !== "000") {
                errAck = ack;
            }
        }

        if (errAck !== null) {
            if (errAck.result === "004") {
                Modal.open(top.T.AlertInfo.OperationFail, errAck.hint, "error");
            } else {
                Modal.open(top.T.AlertInfo.OperationFail, errAck.protoContent, "error");
            }
            return false;
        } else {
            Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.DelSuccess, "ok");
            return true;
        }
    }

    return {
        init: init,
        push: push,
        del: del,
        get: get,
        evaluation: evaluation,
        update: update,
        save: save,
        refresh: refresh,
        name_valInit: name_valInit,
        instanceAdd: instanceAdd,
        instanceDel: instanceDel
    };

}());
